package dao;

import model.entity.Carrinho;
import model.entity.Jogo;
import model.entity.Usuario;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author CesarFrantz
 */
public class CarrinhoDAO {

    private Session sessao;
    private Transaction trans;
    private UsuarioDAO usuarioDAO;
    private JogoDAO jogoDAO;

    public CarrinhoDAO() {
    }

    public void addJogoCarrinho(int idjogo) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            trans = sessao.beginTransaction();
            Carrinho c = new Carrinho();

            Integer idusuario = (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id") != null) ? (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id") : null;
            if (idusuario == null) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "", "Você precisa estar logado para prosseguir!"));
                FacesContext.getCurrentInstance().getExternalContext().redirect("login.xhtml");
            }
            sessao = HibernateUtil.getSessionFactory().openSession();
            Transaction tx = sessao.beginTransaction();

            sessao.createSQLQuery("INSERT INTO carrinho VALUES (null, " + idusuario + "," + idjogo + ")").executeUpdate();
            tx.commit();

            sessao.persist(c);
            trans.commit();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            sessao.close();
        }
    }

    public void removeJogoCarrinho(int idjogo) {
        Integer idusuario = (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id") != null) ? (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id") : '1';

        sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = sessao.beginTransaction();
        sessao.createQuery("DELETE FROM Carrinho c WHERE c.idjogo=" + idjogo + " and idusuario=" + idusuario + ")").executeUpdate();
        tx.commit();
        sessao.close();
    }

}
